package com.hq.communication;

/**
 * 奇数执行完等待偶数线程 偶数执行完等待奇数线程
 * 使用object wait  notify   方式实现线程之间的等待和唤醒操作
 *
 * @author hq
 */
@SuppressWarnings("all")
public class ObjectOddEven {
    static int i = 0;
    static Object object = new Object();
    static Thread thread1;
    static Thread thread2;

    public static void objectOdd() {
        while (i < 10) {
            synchronized (object) {
                System.out.println("！！！！！！");
                if (i % 2 == 1) {
                    System.out.println(Thread.currentThread().getName() + ":这是奇数" + i++);
                    object.notify();  //唤醒偶数线程
                } else {
                    try {
                        object.wait(); //不是奇数就等待 偶数线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void objectEven() {
        while (i < 10) {
            synchronized (object) {
                System.out.println("===================");
                if (i % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ":这是偶数" + i++);
                    object.notify();  //唤醒偶数线程
                } else {
                    try {
                        object.wait(); //不是奇数就等待 偶数线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }



}
